﻿using System;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using AB.ServiceDirectory.BO;
using AB.ServiceDirectory.Entities;

namespace AB.ServiceDirectory.Design.TeamMaintenance
{
    public partial class TeamDetails : Page
    {
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitSaveMode();
                LoadCountries();
            }
        }

        /// <summary>
        /// Inits the save mode.
        /// </summary>
        private void InitSaveMode()
        {
            int departmentId;
            if (int.TryParse(Request.Params["departmentId"], out departmentId))
            {
                if (DepartmentBO.GetDepartmentById(departmentId) != null)
                {
                    ButtonSave.Enabled = true;
                    ButtonSave.CommandName = "new";
                    HiddenFieldDepartmentId.Value = departmentId.ToString(CultureInfo.CurrentCulture);

                    LoadDefaultValues();
                }
            }

            int teamId;
            if (int.TryParse(Request.Params["teamId"], out teamId))
            {
                Team team = TeamBO.GetTeamById(teamId);
                if (team != null)
                {
                    ButtonSave.Enabled = true;
                    ButtonSave.CommandName = "edit";
                    ButtonInactive.Visible = true;
                    HiddenFieldTeamId.Value = teamId.ToString(CultureInfo.CurrentCulture);
                    HiddenFieldTeamName.Value = team.TeamName;
                    HiddenFieldDepartmentId.Value = team.DepartmentId.ToString(CultureInfo.CurrentCulture);

                    LoadTeamDetails();
                }
            }
        }

        /// <summary>
        /// Loads the team details.
        /// </summary>
        private void LoadTeamDetails()
        {
            int teamId;
            if (int.TryParse(HiddenFieldTeamId.Value, out teamId))
            {
                Team team = TeamBO.GetTeamById(teamId);

                HiddenFieldTeamId.Value = team.TeamId.ToString(CultureInfo.CurrentCulture);
                HiddenFieldDepartmentId.Value = team.DepartmentId.ToString(CultureInfo.CurrentCulture);
                HiddenFieldTeamName.Value = team.TeamName;

                if (team.Contact != null)
                {
                    Contact contact = team.Contact;
                    HiddenFieldContactId.Value = contact.ContactId.ToString(CultureInfo.CurrentCulture);
                    TextBoxLeadContact.Text = string.Format(CultureInfo.CurrentCulture, "{0} {1}", contact.FirstName,
                                                            contact.Surname);
                }

                if (team.Address != null)
                {
                    Address address = team.Address;
                    HiddenFieldAddressId.Value = address.AddressId.ToString(CultureInfo.CurrentCulture);
                    TextBoxAddressLine1.Text = address.AddressLine;
                    TextBoxAddressLine2.Text = address.AddressLine2;
                    TextBoxAddressLine3.Text = address.AddressLine3;
                    DropDownListNationCounty.SelectedValue = team.CountryId;
                    TextBoxPostcode.Text = address.Postcode;
                }

                if (team.BusinessType != null)
                {
                    BusinessType business = team.BusinessType;
                    HiddenFieldBusinessId.Value = business.BusinessId.ToString(CultureInfo.CurrentCulture);
                    TextBoxSicCode.Text = business.SICCode;
                    TextBoxTypeOfBusiness.Text = business.BusinessName;
                }

                TextBoxTeamName.Text = team.TeamName;
                TextBoxFullDescription.Text = team.FullDescription;
                TextBoxShortDescription.Text = team.ShortDescription;
                TextBoxFax.Text = team.Fax;
                TextBoxEmail.Text = team.Email;
                TextBoxCounty.Text = team.County;
                TextBoxCityTown.Text = team.CityTown;
                TextBoxWebAddress.Text = team.WebAddress;
                TextBoxPhoneNumber.Text = team.PhoneNumber;
                ButtonInactive.Visible = team.IsActive;
            }
        }

        /// <summary>
        /// Loads the default values.
        /// </summary>
        private void LoadDefaultValues()
        {
            int departmentId;
            if (int.TryParse(HiddenFieldDepartmentId.Value, out departmentId))
            {
                Organization organisation = DepartmentBO.GetDepartmentById(departmentId).Directorate.Organization;

                // Business default values from the Organization
                BusinessType business = organisation.BusinessType;
                TextBoxTypeOfBusiness.Text = business.BusinessName;
                TextBoxSicCode.Text = business.SICCode;
                HiddenFieldBusinessId.Value = business.BusinessId.ToString(CultureInfo.CurrentCulture);

                // Web Address default values from the Organization
                TextBoxWebAddress.Text = organisation.WebAddress;
            }
        }

        /// <summary>
        /// Binds the drop down list country.
        /// </summary>
        private void LoadCountries()
        {
            DropDownListNationCounty.DataSource = CountryBO.SelectCountries();
            DropDownListNationCounty.DataBind();
        }

        /// <summary>
        /// Handles the Click event of the ButtonSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonSave_Click(object sender, EventArgs e)
        {
            Team team = SelectTeam();
            bool result = ButtonSave.CommandName.Equals("new") ? TeamBO.AddTeam(team) : TeamBO.EditTeam(team);
            if (result)
            {
                Response.Redirect(string.Format(CultureInfo.CurrentCulture,
                                                "~/DepartmentsMaintenance/DepartmentDetails.aspx?departmentId={0}#DetailsPanel02",
                                                team.DepartmentId));
            }
        }

        /// <summary>
        /// Handles the Click event of the ButtonTypeOfBussiness control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonTypeOfBusiness_Click(object sender, EventArgs e)
        {
            BusinessLookup.Popup();
        }

        /// <summary>
        /// Handles the Click event of the ButtonContactLookup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonContactLookup_Click(object sender, EventArgs e)
        {
            ContactLookupPopup.Popup();
        }

        /// <summary>
        /// Handles the Click event of the ButtonPostcodeLookup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void ButtonPostcodeLookup_Click(object sender, EventArgs e)
        {
            AddressLookupPopup.Popup();
        }

        /// <summary>
        /// Gets the team from fields in page
        /// </summary>
        /// <returns></returns>
        private Team SelectTeam()
        {
            var team = new Team();
            if (ButtonSave.CommandName.Equals("edit"))
            {
                team.TeamId = int.Parse(HiddenFieldTeamId.Value, CultureInfo.CurrentCulture);
            }

            team.TeamName = TextBoxTeamName.Text;
            team.ShortDescription = TextBoxShortDescription.Text;
            team.CityTown = TextBoxCityTown.Text;
            team.County = TextBoxCounty.Text;
            team.CountryId = DropDownListNationCounty.SelectedValue;
            team.FullDescription = TextBoxFullDescription.Text;
            team.PhoneNumber = string.IsNullOrEmpty(TextBoxPhoneNumber.Text) ? string.Empty : TextBoxPhoneNumber.Text;
            team.Fax = string.IsNullOrEmpty(TextBoxFax.Text) ? string.Empty : TextBoxFax.Text;
            team.Email = string.IsNullOrEmpty(TextBoxEmail.Text) ? string.Empty : TextBoxEmail.Text;
            team.WebAddress = string.IsNullOrEmpty(TextBoxWebAddress.Text) ? string.Empty : TextBoxWebAddress.Text;

            team.ContactId = string.IsNullOrEmpty(HiddenFieldContactId.Value)
                                 ? (int?)null
                                 : int.Parse(HiddenFieldContactId.Value, CultureInfo.CurrentCulture);
            team.AddressId = string.IsNullOrEmpty(HiddenFieldAddressId.Value)
                                 ? (int?)null
                                 : int.Parse(HiddenFieldAddressId.Value, CultureInfo.CurrentCulture);
            team.BusinessId = string.IsNullOrEmpty(HiddenFieldBusinessId.Value)
                                  ? (int?)null
                                  : int.Parse(HiddenFieldBusinessId.Value, CultureInfo.CurrentCulture);
            team.DepartmentId = int.Parse(HiddenFieldDepartmentId.Value, CultureInfo.CurrentCulture);
            return team;
        }

        /// <summary>
        /// Handles the Command event of the ButtonInactive control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonInactive_Command(object sender, CommandEventArgs e)
        {
            int teamId;
            if (int.TryParse(HiddenFieldTeamId.Value, out teamId))
            {
                TeamBO.SetTeamStatus(teamId, false);
                ButtonInactive.Visible = false;
            }
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the RadioButtonListAddress control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void RadioButtonListAddress_SelectedIndexChanged(object sender, EventArgs e)
        {
            int departmentId;
            if (int.TryParse(HiddenFieldDepartmentId.Value, out departmentId))
            {
                Department department = DepartmentBO.GetDepartmentById(departmentId);
                if (department != null)
                {
                    Address address = RadioButtonListAddress.SelectedValue.Equals("Organization")
                                          ? department.Directorate.Organization.Address
                                          : department.Address;
                    if (address == null)
                    {
                        return;
                    }

                    TextBoxAddressLine1.Text = address.AddressLine;
                    TextBoxAddressLine2.Text = address.AddressLine2;
                    TextBoxAddressLine3.Text = address.AddressLine3;
                    TextBoxPostcode.Text = address.Postcode;
                    HiddenFieldAddressId.Value = address.AddressId.ToString(CultureInfo.CurrentCulture);
                }
            }
        }

        /// <summary>
        /// Handles the Command event of the ButtonBack control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
        protected void ButtonBack_Command(object sender, CommandEventArgs e)
        {
            int departmentId;
            if (int.TryParse(HiddenFieldDepartmentId.Value, out departmentId))
            {
                Response.Redirect(string.Format(CultureInfo.CurrentCulture,
                                                "~/DepartmentsMaintenance/DepartmentDetails.aspx?departmentId={0}#DetailsPanel02",
                                                departmentId));
            }
        }
    }
}